﻿using Autofac.Core;
using EWC.Core.DependencyInjection;
using EWC.Core.Util.Settings;
using EWC.HIS.Domain.Data.Enums;
using EWC.HIS.Domain.Data.Repositories;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Threading;
using System.Threading.Tasks;

namespace EWC.HIS.Dapper.Data
{

    public class DbContext : IDbContext, IScopedDependency
    {
        /// <summary>
        /// 数据库连接设置
        /// </summary>
        public EDbConnStr DbConnStr { get; set; }

        private SqlConnection _sqlConnection;

        public DbTransaction Transaction { get; set; }

        private bool _disposed;

        // 构造函数
        public DbContext()
        {

        }

        // 定义连接字符串键值
        private const string HIS_CONNECTION_STRING_KEY = "ConnectionStrings:HIS";
        private const string EMGDB_CONNECTION_STRING_KEY = "ConnectionStrings:EmgDB";

        // 添加一个映射表，将连接字符串键值与枚举类型对应
        private readonly static Dictionary<EDbConnStr, string> ConnectionStringMap = new Dictionary<EDbConnStr, string>
    {
        { EDbConnStr.HIS, HIS_CONNECTION_STRING_KEY },
        { EDbConnStr.EmgDB, EMGDB_CONNECTION_STRING_KEY },
    };

        /// <summary>
        /// 获取数据库上下文对象
        /// </summary>
        /// <returns></returns>
        public async Task<IDbConnection> GetConnectionAsync()
        {
            var _sqlConnection = await GetSqlConnectionAsync();
            return _sqlConnection;
        }

        /// <summary>
        /// 获取 SqlConnection 对象
        /// </summary>
        /// <returns></returns>
        private async Task<SqlConnection> GetSqlConnectionAsync()
        {
            // 获取数据库连接字符串
            var _dbConnectionString = AppSettings.GetValue(ConnectionStringMap[DbConnStr]);

            if (_sqlConnection == null)
            {
                // 创建 SqlConnection 对象
                var conn = new SqlConnection(_dbConnectionString);
                // 打开数据库连接
                await conn.OpenAsync();
                _sqlConnection = conn;
            }

            return _sqlConnection;
        }

        /// <summary>
        /// 开启事务
        /// </summary>
        public async ValueTask<DbTransaction> BeginTransactionAsync()
        {
            // 获取 SqlConnection 对象
            var _sqlConnection = await GetSqlConnectionAsync();

            // 开启事务
            Transaction = await _sqlConnection.BeginTransactionAsync();

            return Transaction;
        }

        /// <summary>
        /// 实现 IDisposable 接口
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// 实现 IAsyncDisposable 接口
        /// </summary>
        /// <returns></returns>
        public async ValueTask DisposeAsync()
        {
            await DisposeAsyncCore();
            Dispose(false);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// 异步释放资源
        /// </summary>
        /// <returns></returns>
        protected virtual async ValueTask DisposeAsyncCore()
        {
            if (!_disposed && _sqlConnection != null)
            {
                await _sqlConnection.DisposeAsync();
                _disposed = true;
            }
        }

        /// <summary>
        ///  释放资源
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    if (_sqlConnection != null)
                    {
                        _sqlConnection.Dispose();
                    }
                }

                _disposed = true;
            }
        }

        /// <summary>
        /// 析构函数
        /// </summary>
        ~DbContext()
        {
            Dispose(false);
        }
    }


}
